<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Card as ACard,
  Image as AImage,
  Tag as ATag,
  Divider as ADivider,
  Comment as AComment,
  Avatar as AAvatar,
  Button as AButton,
  message,
  Timeline as ATimeline,
  TimelineItem as ATimelineItem,
  Modal as AModal,
  Input as AInput,
} from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  UserOutlined,
  WarningOutlined,
  CheckOutlined,
  CloseOutlined,
} from '@ant-design/icons-vue'
import { getPostDetail, approvePost, rejectPost } from '@/api/manger'
import { useUserStore } from '@/stores/user'

interface Reply {
  id: number
  userId: number
  username: string | null
  userAvatar: string | null
  content: string
  isAnonymity: number
  createTime: string
  replyCount: number
  replies: Reply[] | null
}

interface Comment {
  id: number
  userId: number
  username: string | null
  userAvatar: string | null
  content: string
  isAnonymity: number
  createTime: string
  replyCount: number
  replies: Reply[] | null
}

interface Report {
  reportId: number
  reporterId: number
  reporterName: string | null
  reporterAvatar: string | null
  reason: string
  reportTime: string
  status: number
}

interface PostDetail {
  id: number
  authorId: number
  authorName: string
  authorAvatar: string
  content: string
  title: string
  type: number
  isAnonymous: number
  postStatus: number
  viewsCount: number
  commentsCount: number
  likesCount: number
  collectsCount: number
  createTime: string
  updateTime: string
  comments: Comment[]
  reportCount?: number
  reports?: Report[]
  [key: `image${number}`]: string | null
}

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const postDetail = ref<PostDetail | null>(null)
const isFromCheck = ref(route.query.from === 'check')
const rejectModalVisible = ref(false)
const rejectReason = ref('')

// 修改帖子类型映射
const postTypes: Record<number, { text: string; color: string }> = {
  0: { text: '其他', color: '' },
  1: { text: '公告', color: 'red' },
  2: { text: '活动', color: 'blue' },
  3: { text: '求助', color: 'orange' },
  4: { text: '二手交易', color: 'green' },
  5: { text: '表白', color: 'pink' },
  6: { text: '失物招领', color: 'purple' },
  7: { text: '校园咨询', color: 'cyan' },
  8: { text: '吐槽', color: 'volcano' },
  9: { text: '学习', color: 'geekblue' },
  10: { text: '反馈与建议', color: 'gold' },
}

const fetchPostDetail = async () => {
  const id = Number(route.params.id)
  if (!id) {
    message.error('帖子ID无效')
    return
  }

  try {
    loading.value = true
    // 检查是否有从举报页面传来的数据
    if (route.query.reportInfo === 'true') {
      const tempReportInfo = localStorage.getItem('tempReportInfo')
      const reportInfo = tempReportInfo ? JSON.parse(tempReportInfo) : null

      const res = await getPostDetail(id)
      if (res.data.code === 200) {
        postDetail.value = {
          ...res.data.data,
          ...(reportInfo || {}), // 合并举报信息
        }
        // 清除临时存储的数据
        localStorage.removeItem('tempReportInfo')
      }
    } else {
      // 正常获取帖子详情
      const res = await getPostDetail(id)
      if (res.data.code === 200) {
        postDetail.value = res.data.data
      }
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    message.error('获取帖子详情失败')
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.back()
}

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString()
}

// 添加获取图片 URL 的辅助函数
const getImageUrl = (key: `image${number}`) => {
  if (!postDetail.value) return ''
  return postDetail.value[key] || ''
}

// 通过审核
const handleApprove = async () => {
  const adminId = userStore.userInfo?.id
  const postId = Number(route.params.id)

  if (!adminId || !postId) {
    message.error('获取信息失败')
    return
  }

  try {
    const res = await approvePost(postId, adminId)
    if (res.data.code === 200) {
      message.success('审核通过')
      router.push('/check')
    }
  } catch (error) {
    console.error('审核操作失败:', error)
    message.error('审核操作失败')
  }
}

// 显示拒绝模态框
const showRejectModal = () => {
  rejectReason.value = ''
  rejectModalVisible.value = true
}

// 拒绝审核
const handleReject = async () => {
  if (!rejectReason.value.trim()) {
    message.error('请输入拒绝原因')
    return
  }

  const adminId = userStore.userInfo?.id
  const postId = Number(route.params.id)

  if (!adminId || !postId) {
    message.error('获取信息失败')
    return
  }

  try {
    const res = await rejectPost(postId, adminId, rejectReason.value.trim())
    if (res.data.code === 200) {
      message.success('已拒绝通过')
      rejectModalVisible.value = false
      router.push('/check')
    }
  } catch (error) {
    console.error('拒绝操作失败:', error)
    message.error('拒绝操作失败')
  }
}

onMounted(() => {
  fetchPostDetail()
})
</script>

<template>
  <div class="post-details">
    <AButton type="link" class="back-button" @click="goBack">
      <ArrowLeftOutlined />
      返回
    </AButton>

    <ACard v-if="postDetail" :loading="loading">
      <!-- 添加审核操作按钮 -->
      <div v-if="isFromCheck" class="audit-actions">
        <AButton type="primary" @click="handleApprove">
          <CheckOutlined />
          通过审核
        </AButton>
        <AButton type="primary" danger @click="showRejectModal">
          <CloseOutlined />
          拒绝审核
        </AButton>
      </div>

      <!-- 帖子头部信息 -->
      <div class="post-header">
        <div class="author-info">
          <AAvatar
            :src="postDetail.authorAvatar"
            :icon="!postDetail.authorAvatar && h(UserOutlined)"
            :size="48"
          />
          <div class="author-meta">
            <h3>{{ postDetail.isAnonymous ? '匿名用户' : postDetail.authorName }}</h3>
            <span class="post-time">{{ formatDate(postDetail.createTime) }}</span>
          </div>
        </div>
        <div class="post-meta">
          <ATag :color="postTypes[postDetail.type]?.color">
            {{ postTypes[postDetail.type]?.text || '未知' }}
          </ATag>
          <ATag :color="postDetail.postStatus === 1 ? 'success' : 'error'">
            {{ postDetail.postStatus === 1 ? '正常' : '已禁用' }}
          </ATag>
        </div>
      </div>

      <!-- 帖子内容 -->
      <div class="post-content">
        <h2 class="post-title">{{ postDetail.title }}</h2>
        <p class="post-text">{{ postDetail.content }}</p>
        <div v-if="postDetail.image1" class="post-images">
          <template v-for="i in 9" :key="i">
            <AImage
              v-if="getImageUrl(`image${i}` as `image${number}`)"
              :src="getImageUrl(`image${i}` as `image${number}`)"
              :width="200"
              class="post-image"
            />
          </template>
        </div>
      </div>

      <!-- 互动数据 -->
      <div class="post-stats">
        <span>浏览 {{ postDetail.viewsCount }}</span>
        <span>评论 {{ postDetail.commentsCount }}</span>
        <span>点赞 {{ postDetail.likesCount }}</span>
        <span>收藏 {{ postDetail.collectsCount }}</span>
      </div>

      <!-- 添加举报信息展示 -->
      <ADivider v-if="postDetail.reports?.length" orientation="left">
        <span class="divider-title">
          <WarningOutlined style="color: #ff4d4f; margin-right: 8px" />
          举报信息 ({{ postDetail.reportCount }} 次)
        </span>
      </ADivider>

      <div v-if="postDetail.reports?.length" class="reports-section">
        <ATimeline>
          <ATimelineItem
            v-for="report in postDetail.reports"
            :key="report.reportId"
            :color="report.status === 1 ? 'red' : 'blue'"
          >
            <ACard class="report-card" size="small">
              <div class="reporter-info">
                <div class="reporter-meta">
                  <AAvatar
                    :src="report.reporterAvatar || undefined"
                    :icon="!report.reporterAvatar && h(UserOutlined)"
                    :size="32"
                  />
                  <span class="reporter-name">{{ report.reporterName || '匿名用户' }}</span>
                </div>
                <span class="report-time">{{ formatDate(report.reportTime) }}</span>
              </div>
              <div class="report-content">
                <div class="report-reason">举报原因：{{ report.reason }}</div>
                <ATag :color="report.status === 1 ? 'red' : 'blue'">
                  {{ report.status === 1 ? '待处理' : '已处理' }}
                </ATag>
              </div>
            </ACard>
          </ATimelineItem>
        </ATimeline>
      </div>

      <ADivider />

      <!-- 评论区 -->
      <div class="comments-section">
        <h3>评论 ({{ postDetail.commentsCount }})</h3>
        <AComment
          v-for="comment in postDetail.comments"
          :key="comment.id"
          :author="comment.isAnonymity ? '匿名用户' : comment.username"
          :avatar="comment.userAvatar || undefined"
          :content="comment.content"
          :datetime="formatDate(comment.createTime)"
        >
          <!-- 回复列表 -->
          <template v-if="comment.replies?.length">
            <AComment
              v-for="reply in comment.replies"
              :key="reply.id"
              :author="reply.isAnonymity ? '匿名用户' : reply.username"
              :avatar="reply.userAvatar || undefined"
              :content="reply.content"
              :datetime="formatDate(reply.createTime)"
            />
          </template>
        </AComment>
      </div>
    </ACard>

    <!-- 添加拒绝模态框 -->
    <AModal
      v-model:visible="rejectModalVisible"
      title="拒绝原因"
      @ok="handleReject"
      okText="确认"
      cancelText="取消"
      :okButtonProps="{ danger: true }"
    >
      <AInput.TextArea
        v-model:value="rejectReason"
        placeholder="请输入拒绝原因"
        :rows="4"
        :maxlength="200"
        show-count
      />
    </AModal>
  </div>
</template>

<style scoped>
.post-details {
  padding: 24px;
  max-width: 1000px;
  margin: 0 auto;
}

.back-button {
  margin-bottom: 16px;
  padding: 0;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.author-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-meta h3 {
  margin: 0;
  font-size: 16px;
  line-height: 1.5;
}

.post-time {
  color: #8c8c8c;
  font-size: 14px;
}

.post-meta {
  display: flex;
  gap: 8px;
}

.post-content {
  margin-bottom: 24px;
}

.post-title {
  margin: 0 0 16px;
  font-size: 24px;
  line-height: 1.4;
}

.post-text {
  font-size: 16px;
  line-height: 1.8;
  margin-bottom: 16px;
  white-space: pre-wrap;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 8px;
  margin-bottom: 24px;
}

.post-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.post-stats {
  display: flex;
  gap: 24px;
  color: #8c8c8c;
}

.comments-section {
  margin-top: 24px;
}

.comments-section h3 {
  margin-bottom: 24px;
  font-size: 18px;
}

:deep(.ant-comment) {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

:deep(.ant-comment-nested) {
  margin-top: 16px;
  margin-left: 24px;
  background: white;
}

.divider-title {
  font-size: 16px;
  font-weight: 500;
  color: #1f1f1f;
  display: flex;
  align-items: center;
}

.reports-section {
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
  margin-bottom: 24px;
}

.report-card {
  margin-bottom: 8px;
  border-radius: 8px;
  background: white;
}

.reporter-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.reporter-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.reporter-name {
  font-weight: 500;
  color: #1f1f1f;
}

.report-time {
  font-size: 12px;
  color: #999;
}

.report-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.report-reason {
  color: #666;
  flex: 1;
  margin-right: 16px;
}

:deep(.ant-timeline-item-content) {
  margin-left: 20px !important;
}

.audit-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}
</style>
